package com.lfs.dispatcher.util;

import com.lfs.interfaces.model.NotifyModel;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.SocketTimeoutException;

public class HttpSendUtil {
	private static Logger log= LoggerFactory.getLogger(HttpSendUtil.class);
	public  static  String sendPost(NotifyModel model, String notifyAdapterUrl) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(600000)
				.setConnectTimeout(600000).setConnectionRequestTimeout(600000).build();//设置请求(10分钟)和传输超时时间(10分钟)
		
		String url = notifyAdapterUrl;
		HttpPost httpPost = new HttpPost(url);
		String paramsStr = JacksonUtils.writeValue(model);
		httpPost.setEntity(new StringEntity(paramsStr, "utf-8"));
		httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
		httpPost.addHeader("Accept", "application/json");
		httpPost.setConfig(requestConfig);
		try {
			CloseableHttpResponse response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				return EntityUtils.toString(entity);
			} else {
				log.error("请求：" + url + "，失败，返回码:" + response.getStatusLine().getStatusCode());
			}
		} catch(SocketTimeoutException e1){
			log.error("请求：" + url + "，超时，e={}", e1);
		}catch (Exception e) {
			log.error("请求：" + url + "，失败，e={}", e);
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				log.error("关闭httpClient失败，e={}", e);
			}
		}
		return null;
	}
}
